package com.hu.video.service.impl;

import com.hu.video.entity.TMessage;
import com.hu.video.entity.TUser;
import com.hu.video.entity.TVideo;
import com.hu.video.entity.vo.CommentedStar;
import com.hu.video.mapper.*;
import com.hu.video.service.IMsgTypeService;
import com.hu.video.service.IStateService;
import com.hu.video.service.IVideoService;
import com.hu.video.service.IUserBlockRelationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class VideoServiceImpl implements IVideoService {


    /*--------------调用mapper------------------*/
    @Autowired
    private TVideoMapper videoMapper;

    @Autowired
    private TUserMapper userMapper;

    @Autowired
    private TMessageMapper msgMapper;

    @Autowired
    private CommentedStarMapper commentedStarMapper;

    /*------------调用service---------------*/
    @Autowired
    private IMsgTypeService msgTypeMService;

    @Autowired
    private IStateService stateService;

    @Autowired
    private IUserBlockRelationsService userBlockRelationsService;

    @Override
    public String addViewSum(Long videoId) {
        int signal = videoMapper.updateVideoViewSumByVideoId(videoId);
        if (signal == 1) {
            return "更新成功";
        } else {
            return "观看次数更新出错";
        }
    }


    @Override
    public List<TVideo> getVideoListByUserId(Long userId, Long currentUserId) {
        List<TVideo> videos = videoMapper.getVideoListByUserId(userId, 4L);
        return filterBlockedUserVideos(videos, currentUserId);
    }

    @Override
    public List<TVideo> getVideoByVideoTypeId(Long videoTypeId, Long currentUserId) {
        List<TVideo> videos = videoMapper.getVideoByVideoTypeId(videoTypeId);
        return filterBlockedUserVideos(videos, currentUserId);
    }

    @Override
    public List<TVideo> getIndexLastVideo(Long currentUserId) {
        List<TVideo> videos = videoMapper.getIndexLastVideo();
        return filterBlockedUserVideos(videos, currentUserId);
    }

    @Override
    public List<TVideo> getIndexRecommendVideo(Long currentUserId) {
        List<TVideo> videos = videoMapper.getIndexRecommendVideo();
        return filterBlockedUserVideos(videos, currentUserId);
    }

    @Override
    public List<TVideo> queryByVideoTitle(String videoTitle, Long currentUserId) {
        List<TVideo> videos = videoMapper.queryByVideoTitle(videoTitle);
        return filterBlockedUserVideos(videos, currentUserId);
    }

    @Override
    public int adminUpdateVideoImage(String s, Long videoId) {
        return videoMapper.adminUpdateVideoImage(s,videoId);
    }

    @Override
    public Long getVideoLastId(String videoTitle) {
        return videoMapper.getVideoLastId(videoTitle);
    }

    @Override
    public int updateVideoImage(String s, Long videoId) {
        return videoMapper.updateVideoImage(s,videoId);
    }

    @Override
    public int updateVideoPath(String path, Long videoId) {
        return videoMapper.updateVideoPath(path,videoId);
    }

    @Override
    public int addVideo(TVideo video) {
        return videoMapper.addVideo(video);
    }

    @Override
    public String addComment(int starNum, Long userId, Long videoId) {
        TVideo video = videoMapper.selectOneByVideoId(videoId);
        TUser user = userMapper.selectByPrimaryKey(video.getUser().getUserId());
        CommentedStar commentedStar = commentedStarMapper.getCommentedStar(userId, videoId);
        TMessage msg = new TMessage();
        if(commentedStar != null) {
            return "你已经参加点评";
        }
        if(user != null && video != null) {
            commentedStarMapper.insertOne(userId, videoId, starNum);
            msg.setMsgTitle("点评提醒");
            msg.setMsgContext("你好！你的主题为《" + video.getVideoTitle() + "》的视频获得用户【" + user.getUserName() + "】的" + starNum + "星点评");
            msg.setMsgType(msgTypeMService.findByTypeName("EvaluateNotice"));
            msg.setMsgState(stateService.getStateByStateId(6L));
            msg.setReceiveUser(video.getUser());
            msgMapper.insertMsg(msg);
            return "点评成功";
        }
        return "不可对自身视频点评";
    }

    @Override
    public String thumbsUp(TUser user, Long videoId) {
        TVideo video = this.getVideoByVideoId(videoId, null); // Assuming currentUserId is not available here, pass null or handle appropriately
        TMessage msg = new TMessage();
        if (user != null && !user.getUserId().equals(video.getUser().getUserId())) {
            try {
                videoMapper.updateVideoPpSumByVideoId(videoId);
                msg.setMsgTitle("点赞提醒");
                msg.setMsgContext("你好! 你的视频《" + video.getVideoTitle() + "》的视频获得用户【" + user.getUserName() + "】的一枚点赞");
                msg.setMsgType(msgTypeMService.findByTypeName("SupportNotice"));
                msg.setMsgState(stateService.getStateByStateId(6L));
                msg.setReceiveUser(video.getUser());
                msgMapper.insertMsg(msg);
                return "点赞成功";
            } catch (Exception e) {
                return "点赞失败";
            }
        } else {
            return "不可对自己视频点赞";
        }
    }

    @Override
    public List<TVideo> getRecommendVideo(int curPage, int pageSize, Long userId, Long currentUserId) {
        int videoCount = videoMapper.selectVideoCount();
        int curIndex = (curPage - 1) * pageSize;
        if (curPage > 0 && pageSize > 0 && curIndex <= videoCount) {
            List<TVideo> videoList = videoMapper.selectRecommendVideo(curIndex, pageSize, userId);
            if (videoList != null) {
                return filterBlockedUserVideos(videoList, currentUserId);
            }
        }
        return null;
    }

    @Override
    public TVideo getVideoByVideoId(Long videoId, Long currentUserId) {
        TVideo video = null;
        if (videoId != 0) {
            video = videoMapper.selectOneByVideoId(videoId);
        }
        if (video != null && currentUserId != null) {
            // 检查当前用户是否屏蔽了视频作者（不看TA 或 全部屏蔽）
            List<Long> blockedUserIds = userBlockRelationsService.getByUserId(currentUserId)
                .stream()
                .filter(block -> block.getBlockType() == 1 || block.getBlockType() == 3)
                .map(block -> block.getBlockedUserId())
                .collect(Collectors.toList());
            if (video.getUser() != null && blockedUserIds.contains(video.getUser().getUserId())) {
                return null;
            }
            
            // 检查视频作者是否屏蔽了当前用户（不让TA看我 或 全部屏蔽）
            List<Long> usersWhoBlockedMe = userBlockRelationsService.getByBlockedUserId(currentUserId)
                .stream()
                .filter(block -> block.getBlockType() == 2 || block.getBlockType() == 3)
                .map(block -> block.getUserId())
                .collect(Collectors.toList());
            if (video.getUser() != null && usersWhoBlockedMe.contains(video.getUser().getUserId())) {
                return null;
            }
        }
        return video;
    }

//    @Override
//    public List<TVideo> getHotVideos(int limit) {
//        return videoMapper.selectHotVideos(limit);
//    }

    @Override
    public List<TVideo> getHotVideos(int limit, Long currentUserId) {
        List<TVideo> videos = videoMapper.selectHotVideos(limit);
        return filterBlockedUserVideos(videos, currentUserId);
    }

    // 过滤被屏蔽用户的视频
    private List<TVideo> filterBlockedUserVideos(List<TVideo> videos, Long currentUserId) {
        if (videos == null || videos.isEmpty() || currentUserId == null) {
            return videos;
        }
        
        // 获取当前用户屏蔽的其他用户（不看TA 或 全部屏蔽）
        List<Long> blockedUserIds = userBlockRelationsService.getByUserId(currentUserId)
            .stream()
            .filter(block -> block.getBlockType() == 1 || block.getBlockType() == 3)
            .map(block -> block.getBlockedUserId())
            .collect(Collectors.toList());
        
        // 获取屏蔽当前用户的用户（不让TA看我 或 全部屏蔽）
        // 需要查找 blockedUserId 为当前用户的记录
        List<Long> usersWhoBlockedMe = userBlockRelationsService.getByBlockedUserId(currentUserId)
            .stream()
            .filter(block -> block.getBlockType() == 2 || block.getBlockType() == 3)
            .map(block -> block.getUserId()) // 这里获取的是发起屏蔽的用户ID
            .collect(Collectors.toList());
        
        return videos.stream()
            .filter(video -> {
                if (video.getUser() == null) return true;
                
                Long videoUserId = video.getUser().getUserId();
                
                // 过滤掉被当前用户屏蔽的用户视频（不看TA 或 全部屏蔽）
                if (blockedUserIds.contains(videoUserId)) {
                    return false;
                }
                
                // 过滤掉当前用户被屏蔽的视频（不让TA看我 或 全部屏蔽）
                if (usersWhoBlockedMe.contains(videoUserId)) {
                    return false;
                }
                
                return true;
            })
            .collect(Collectors.toList());
    }

    @Override
    public List<TVideo> getAllVideoListByUserId(Long userId) {
        return videoMapper.getAllVideoListByUserId(userId);
    }

    @Override
    public int updateVideo(TVideo video) {
        return videoMapper.updateByPrimaryKeySelective(video);
    }

    @Override
    public int deleteVideo(Long videoId) {
        return videoMapper.deleteByPrimaryKey(videoId);
    }
}

